package game.socket;

import dou.net.socket.IServerSocket;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * 为一个套接字服务对象创建一个独立线程运行提供支持
 * @author wizardc
 */
public class ServerSocketThread extends Thread
{
    private static Logger logger = LogManager.getLogger("GameServer");

    // 记录运行的套接字服务对象
    private IServerSocket _serverSocket;
    // 记录该套接字服务监听的地址
    private String _host;
    // 记录该套接字服务监听的端口
    private int _port;
    // 记录阻塞计数对象
    private CountDownLatch _latch;

    /**
     * 创建一个 ServerSocketThread 对象
     * @param serverSocket 运行的套接字服务对象
     * @param host 套接字服务监听的地址
     * @param port 套接字服务监听的端口
     * @param latch 阻塞计数对象
     */
    public ServerSocketThread(IServerSocket serverSocket, String host, int port, CountDownLatch latch)
    {
        _serverSocket = serverSocket;
        _host = host;
        _port = port;
        _latch = latch;
    }

    @Override
    public void run()
    {
        logger.info("ServerSocket start at host [" + _host + "] and port [" + _port + "]");
        _latch.countDown();
        try
        {
            // startService 方法会阻塞线程
            _serverSocket.startService(_host, _port);
        }
        catch(IOException exception)
        {
            exception.printStackTrace();
        }
    }
}
